package tools

import (
	"encoding/csv"
	"encoding/json"
	"os"
)

// ReadCSVData reads CSV data from a file and returns it as key-value pairs
// Parameters:
//   - filePath: path to the CSV file
//   - orderNum: maximum number of records to read (-1 for all records)
//   - exitTitle: whether to skip the first row (header)
//   - keyIndex: column index to use as key
// Returns:
//   - [][2][]byte: array of key-value pairs where [0] is key and [1] is value
//   - error: any error that occurred during reading
func ReadCSVData(filePath string, orderNum int, exitTitle bool, keyIndex int) ([][2][]byte, error) {
	file, err := os.Open(filePath)
	if err != nil {
		return nil, err
	}
	defer file.Close()

	reader := csv.NewReader(file)
	reader.FieldsPerRecord = -1 // Allow variable number of fields

	records, err := reader.ReadAll()
	if err != nil {
		return nil, err
	}

	if exitTitle && len(records) > 0 {
		records = records[1:]
	}

	if orderNum > 0 && orderNum < len(records) {
		records = records[:orderNum]
	}

	var data [][2][]byte
	for _, record := range records {
		if len(record) > keyIndex {
			key := []byte(record[keyIndex])

			valueFields := make([]string, 0, len(record)-1)
			for i, field := range record {
				if i != keyIndex {
					valueFields = append(valueFields, field)
				}
			}

			value, err := json.Marshal(valueFields)
			if err != nil {
				return nil, err
			}

			data = append(data, [2][]byte{key, value})
		}
	}

	return data, nil
}